<template>
  <div class="dict-manage">
    <div class="page-header">
      <h2>字典管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加字典项
        </el-button>
        <el-button type="danger" :disabled="!selectedDicts.length" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="字典名称">
          <el-input v-model="searchForm.name" placeholder="请输入字典名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        stripe 
        style="width: 100%" 
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="字典编码" width="120" />
        <el-table-column prop="name" label="字典名称" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="明细数量" width="100">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.dictDataCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">
              <el-icon><View /></el-icon>
              明细
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加字典项' : '编辑字典项'"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        style="padding-right: 20px"
      >
        <el-form-item label="字典编码" prop="code">
          <el-input v-model="form.code" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 字典明细对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="字典明细管理"
      width="900px"
      @close="handleDetailDialogClose"
    >
      <div class="detail-header">
        <h3>字典类型：{{ currentDictType?.dictName }} ({{ currentDictType?.dictType }})</h3>
        <el-button type="primary" size="small" @click="handleAddDetail">
          <el-icon><Plus /></el-icon>
          添加明细
        </el-button>
      </div>

      <!-- 字典明细表格 -->
      <el-table 
        :data="detailTableData" 
        border 
        stripe 
        style="width: 100%; margin-top: 15px"
        v-loading="detailLoading"
      >
        <el-table-column prop="code" label="字典明细编码" width="120" />
        <el-table-column prop="name" label="明细名称" width="120" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditDetail(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteDetail(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 字典明细添加/编辑对话框 -->
    <el-dialog
      v-model="detailFormDialogVisible"
      :title="detailFormType === 'add' ? '添加字典明细' : '编辑字典明细'"
      width="500px"
    >
      <el-form
        ref="detailFormRef"
        :model="detailForm"
        :rules="detailRules"
        label-width="80px"
      >
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="detailForm.dictLabel" />
        </el-form-item>
        <el-form-item label="字典值" prop="dictValue">
          <el-input v-model="detailForm.dictValue" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="detailForm.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="detailForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-radio-group v-model="detailForm.isDefault">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="detailForm.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailFormDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDetailSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Edit, Search, Refresh, View } from '@element-plus/icons-vue';
import {
  getDictTypeListAPI,
  addDictTypeAPI,
  updateDictTypeAPI,
  deleteDictTypeAPI
} from '@/api/dictType';
import {
  getDictDataListAPI,
  addDictDataAPI,
  updateDictDataAPI,
  deleteDictDataAPI
} from '@/api/dictData';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const selectedDicts = ref([]);

// 搜索表单
const searchForm = reactive({
  name: ''
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框
const dialogVisible = ref(false);
const dialogType = ref('add');
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: '',
  dictType: '',
  dictName: '',
  status: 1,
  remark: ''
});

// 表单验证规则
const rules = {
  dictType: [
    { required: true, message: '请输入字典编码', trigger: 'blur' }
  ],
  dictName: [
    { required: true, message: '请输入字典名称', trigger: 'blur' }
  ]
};

// 字典明细相关数据
const detailDialogVisible = ref(false);
const detailFormDialogVisible = ref(false);
const detailTableData = ref([]);
const detailLoading = ref(false);
const currentDictType = ref(null);
const detailFormType = ref('add');
const detailFormRef = ref(null);

// 字典明细表单
const detailForm = reactive({
  id: '',
  code: '',
  name: '',
  sort: 0,
  status: 1
});

// 字典明细表单验证
const detailRules = {
  dictLabel: [
    { required: true, message: '请输入字典标签', trigger: 'blur' }
  ],
  dictValue: [
    { required: true, message: '请输入字典值', trigger: 'blur' }
  ]
};

// 获取字典列表
const getDictTypeList = async () => {
  loading.value = true;
  try {
    const res = await getDictTypeListAPI({
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name
    });
    console.log('API响应数据:', res);
    
    if (res.code === 200) {
      tableData.value = res.data.records || [];
      pagination.total = res.data.total || 0;
      console.log('表格数据:', tableData.value);
    } else {
      ElMessage.error(res.message || '获取字典列表失败');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取字典列表失败:', error);
    ElMessage.error('获取字典列表失败');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getDictTypeList();
};

// 重置
const handleReset = () => {
  searchForm.name = '';
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getDictTypeList();
};

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getDictTypeList();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedDicts.value = selection;
};

// 添加字典
const handleAdd = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
  Object.assign(form, {
    id: '',
    dictType: '',
    dictName: '',
    status: 1,
    remark: ''
  });
};

// 编辑字典
const handleEdit = (row) => {
  dialogType.value = 'edit';
  dialogVisible.value = true;
  Object.assign(form, {
    ...row,
    status: Number(row.status)
  });
};

// 删除字典
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除字典类型 "${row.dictName}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteDictTypeAPI({ id: row.id });
      if (res.code === 200) {
        ElMessage.success('删除成功');
        getDictTypeList();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedDicts.value.length === 0) {
    ElMessage.warning('请选择要删除的字典项');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedDicts.value.length} 个字典项吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedDicts.value.map(item => item.id);
      const res = await deleteDictTypeAPI({ ids });
      if (res.code === 200) {
        ElMessage.success('批量删除成功');
        getDictTypeList();
      } else {
        ElMessage.error(res.message || '批量删除失败');
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {});
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    const isEdit = dialogType.value === 'edit';
    const api = isEdit ? updateDictTypeAPI : addDictTypeAPI;
    const params = {
      ...form,
      id: isEdit ? form.id : undefined
    };

    const res = await api(params);
    if (res.code === 200) {
      ElMessage.success(isEdit ? '修改成功' : '添加成功');
      dialogVisible.value = false;
      getDictTypeList();
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 查看字典明细
const handleViewDetail = async (row) => {
  currentDictType.value = row;
  detailDialogVisible.value = true;
  console.log('获取字典明细，主表ID:', row.id, '字典编码:', row.dictType);
  await getDictDataList(row.id);
};

// 获取字典明细列表
// 获取字典明细列表
const getDictDataList = async (dictId) => {
  detailLoading.value = true;
  try {
    const params = {
      page: 1,           // 字典明细通常不需要分页，固定为第1页
      size: 100,         // 设置一个较大的值获取所有数据
      dictId: dictId
    };
    
    console.log('请求字典明细参数:', params);
    
    const res = await getDictDataListAPI(params);
    console.log('字典明细完整响应:', res);
    console.log('res.data 类型:', typeof res.data);
    console.log('res.data 内容:', res.data);
    
    if (res.code === 200) {
      // 安全处理数据
      if (Array.isArray(res.data)) {
        // 如果 data 直接是数组
        detailTableData.value = res.data;
      } else if (res.data && res.data.records && Array.isArray(res.data.records)) {
        // 如果 data 是分页对象，包含 records 数组
        detailTableData.value = res.data.records;
      } else if (res.data && res.data.list && Array.isArray(res.data.list)) {
        // 如果 data 包含 list 数组
        detailTableData.value = res.data.list;
      } else {
        // 其他情况，设置为空数组
        console.warn('未知的数据结构，使用空数组:', res.data);
        detailTableData.value = [];
      }
    } else {
      ElMessage.error(res.message || '获取字典明细失败');
      detailTableData.value = [];
    }
    
    console.log('最终明细数据:', detailTableData.value);
    
  } catch (error) {
    console.error('获取字典明细失败:', error);
    ElMessage.error('获取字典明细失败');
    detailTableData.value = [];
  } finally {
    detailLoading.value = false;
  }
};

// 添加字典明细
const handleAddDetail = () => {
  detailFormType.value = 'add';
  detailFormDialogVisible.value = true;
  Object.assign(detailForm, {
    id: '',
    dictType: currentDictType.value.dictType,
    dictLabel: '',
    dictValue: '',
    sortOrder: 0,
    status: 1,
    isDefault: 0,
    remark: ''
  });
};

// 编辑字典明细
const handleEditDetail = (row) => {
  detailFormType.value = 'edit';
  detailFormDialogVisible.value = true;
  Object.assign(detailForm, {
    ...row,
    status: Number(row.status),
    isDefault: Number(row.isDefault)
  });
};

// 删除字典明细
const handleDeleteDetail = (row) => {
  ElMessageBox.confirm(
    `确定要删除字典明细 "${row.dictLabel}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteDictDataAPI({ id: row.id });
      if (res.code === 200) {
        ElMessage.success('删除成功');
        getDictDataList(currentDictType.value.dictType);
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  });
};

// 提交字典明细表单
const handleDetailSubmit = async () => {
  if (!detailFormRef.value) return;
  
  try {
    await detailFormRef.value.validate();
    const isEdit = detailFormType.value === 'edit';
    const api = isEdit ? updateDictDataAPI : addDictDataAPI;
    
    const res = await api(detailForm);
    if (res.code === 200) {
      ElMessage.success(isEdit ? '修改成功' : '添加成功');
      detailFormDialogVisible.value = false;
      getDictDataList(currentDictType.value.dictType);
    } else {
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 关闭字典明细对话框
const handleDetailDialogClose = () => {
  currentDictType.value = null;
  detailTableData.value = [];
};

// 初始化
onMounted(() => {
  console.log('组件挂载，开始获取字典列表');
  getDictTypeList();
});
</script>

<style scoped>
.dict-manage {
  padding: 15px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 5px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-container {
  background-color: #fff;
  padding: 12px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.detail-header h3 {
  margin: 0;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dict-manage {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .search-form {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
}
</style>